/***************************************************************************
 创建者: 华磊
 开始时间: 2020.8.14
 copyright: (C) 华友高科
 修改说明: (每次有修改就添加一条，带有 修改人，修改时间，修改描述)
 example (1) hualei 2020.5.8 类的具体实现代码编写

 ***************************************************************************/
#include "testform.h"
#include "ui_testform.h"
#include "robotbase.h"

#include "robotcontrol.h"
#include <QMessageBox>
extern RobotControl* robCtl;

testForm::testForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::testForm)
{

    versionInfo.componentName="EcatTest_testForm";
    versionInfo.componentVersion="V1.0";
    versionInfo.publishDate="2018.10.27";

    ui->setupUi(this);
   // resize(300,300);

    manual_input=false;
    manual_dir=false;
    getpos = 123456;

    timer = new QTimer();

    if(1)
    {
        for(int j=0;j< 16 ; j++)
        {
            statusWord_box[j]=new QCheckBox(ui->groupBox_statusWord);
            statusWord_box[j]->setGeometry(5, 20+22*j,250, 20);

            controlWord_box[j]=new QCheckBox(ui->groupBox_controlWord);
            controlWord_box[j]->setGeometry(5, 20+22*j,250, 20);
        }
        statusWord_box[0]->setText( "0ready to switch on" );
        statusWord_box[1]->setText( "1switch on" );
        statusWord_box[2]->setText( "2operation enabled" );
        statusWord_box[3]->setText( "3fault" );
        statusWord_box[4]->setText( "4voltage enabled" );
        statusWord_box[5]->setText( "5quick stop" );
        statusWord_box[6]->setText( "6switch on disabled" );
        statusWord_box[7]->setText( "7warning" );
        statusWord_box[8]->setText( "8-" );
        statusWord_box[9]->setText( "9remote" );
        statusWord_box[10]->setText( "10target reach" );
        statusWord_box[11]->setText( "11internal limit active" );
        statusWord_box[12]->setText( "12homing attained" );
        statusWord_box[13]->setText( "13homing error" );
        statusWord_box[14]->setText( "14－" );
        statusWord_box[15]->setText( "15home find" );

        controlWord_box[0]->setText( "0switch on" );
        controlWord_box[1]->setText( "1enable voltage" );
        controlWord_box[2]->setText( "2quick stop 0valid" );
        controlWord_box[3]->setText( "3enable operation" );
        controlWord_box[4]->setText( "4-homing start" );
        controlWord_box[5]->setText( "5-" );
        controlWord_box[6]->setText( "6-" );
        controlWord_box[7]->setText( "7fault reset" );
        controlWord_box[8]->setText( "8halt" );
        controlWord_box[9]->setText( "9-" );
        controlWord_box[10]->setText( "10-" );
        controlWord_box[11]->setText( "11-" );
        controlWord_box[12]->setText( "12-" );
        controlWord_box[13]->setText( "13-" );
        controlWord_box[14]->setText( "14－" );
        controlWord_box[15]->setText( "15－" );

        //   int i=0;
        for(int j=0;j< 32 ; j++)
        {
            virtual_di_box[j]=new QCheckBox(ui->groupBox_di_virtual);
            virtual_di_box[j]->setGeometry(5, 20+22*j,50, 20);
            virtual_di_box[j]->setText( QString::number(j) );
            connect(  virtual_di_box[j], SIGNAL(toggled(bool)), this, SLOT(setVirtualDiState(bool)));
        }
        for(int j=0;j< 32 ; j++)
        {
            di_box[j]=new QCheckBox(ui->groupBox_di);
            di_box[j]->setGeometry(5, 20+22*j,50, 20);
            di_box[j]->setText( QString::number(j) );
        }

        for(int j=0; j<32; j++)
        {
            do_box[j]=new QCheckBox(ui->groupBox_do);
            do_box[j]->setGeometry(5,20+22*j,50,20);
            do_box[j]->setText( QString::number(j) );
            //不能使用　toggled，状态变化，而不是被点击也会触发，导致ＢＵＧ。
//            connect(  do_box[j], SIGNAL(toggled(bool)), this, SLOT(setDoDiState(bool)));
            connect(  do_box[j], SIGNAL(clicked(bool)), this, SLOT(setDoValue(bool)));
        }

        for(int j=0; j< 32 ; j++)
        {
            ai_box[j] =new QLineEdit(ui->groupBox_ai);
            ai_box[j]->setGeometry(5, 20+22*j, 50, 20);
            ai_box[j]->setText( QString::number(j) );
        }

        for(int j=0; j< 32 ; j++)
        {
            ao_box[j]=new QLineEdit(ui->groupBox_ao);
            ao_box[j]->setGeometry(5, 20+22*j,50,20);
            ao_box[j]->setText( QString::number(j) );
        }

        for(int j=0; j< 12 ; j++)
        {
            axis_box[j]=new QLabel(ui->tab);
            axis_box[j]->setGeometry(ui->label_master_state->x(), ui->label_master_state->y()+30+20*j,ui->label_master_state->width(),20);
            axis_box[j]->setText( "axis" );
        }
    }

    connect(timer , SIGNAL(timeout()), this , SLOT( timeoutDo()) );
//    timer->start(100);

}

testForm::~testForm()
{
    delete ui;
}

int testForm::readVersion(std::vector <ComponentVersion> &componentVersionList)
{

    componentVersionList.push_back(versionInfo);
    return 1;
}

void testForm::timeoutDo()
{
    static int counttt=0;
    counttt++;
    if( counttt< 30 )
        return;//启动延时

    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value(),NULL );
    if(rob==NULL)
        return ;


    if(NULL==rob->logicRobotIo)
    {
        return ;
    }

    if(!rob->logicRobotIo->isInitialStatus())
    {
        return ;
    }

    static int state=123456;
    static int pos_count_2 = 0;
    static int pos_count_1 = 0;
    pos_count_1++;
    if( pos_count_1 >50){//10*20
        //    qDebug()<<"ui  thread: "<<  rob->IO->ioDo <<   rob->IO->ioDi;
        ui->label_5->setText(QString("加速度:%1").arg(ui->horizontalSlider->value()));


#if D_IO_USE_VECTOR
        for(int j=0; j< rob->IO->ioDi.size() ; j++)
        {
            QCheckBox* box= (QCheckBox*)ui->groupBox_di->children().at(j);
            box->setChecked(   rob->IO->ioDi[j]  );
        }
        for(int j=0; j< rob->IO->ioAi.size() ; j++)
        {
            ai_box[j]->setText( QString::number(  (double)(rob->IO->ioAi[j]) ));
        }

        for(int j=0; j< rob->IO->ioDo.size() ; j++)
        {
            QCheckBox* box= (QCheckBox*)ui->groupBox_do->children().at(j);
            box->setChecked(   rob->IO->ioDo[j]  );
        }

        for(int j=0; j< rob->IO->ioAo.size() ; j++)
        {
            float val =   ao_box[j]->text().toFloat() ;
            if( val<=2.0  && val>=0 )
                rob->IO->ioAo[j] = val;
        }
#else
        for(int j=0; j< rob->logicRobotIo->diCount ; j++)
        {
            if(j<32)
            {
            QCheckBox* box= (QCheckBox*)ui->groupBox_di->children().at(j);
            box->setChecked(   rob->logicRobotIo->ioDi[j]  );
            }
        }
        for(int j=0; j< rob->logicRobotIo->aiCount ; j++)
        {
            if(j<32)
            {
            ai_box[j]->setText( QString::number(  (double)(rob->logicRobotIo->ioAi[j]) ));
            }
        }

//        if( pos_count_2<rob->IO->doCount )
//        {
//            pos_count_2++;
//            if( rob->IO->ioDo[pos_count_2] )
//                rob->IO->ioDo[pos_count_2]= 0;
//            else
//                rob->IO->ioDo[pos_count_2]= 1;
//        }else{
//            pos_count_2=0;
//        }

        for(int j=0; j< rob->logicRobotIo->doCount ; j++)
        {
            if(j<32)
            {
            QCheckBox* box= (QCheckBox*)ui->groupBox_do->children().at(j);
            box->setChecked(   rob->logicRobotIo->ioDo[j]  );
            }
        }

        for(int j=0; j< rob->logicRobotIo->aoCount ; j++)
        {
            if(j<32)
            {
            float val =   ao_box[j]->text().toFloat();
//            if( val<=2.0  && val>=0 )
                rob->logicRobotIo->ioAo[j] = val;
            }
        }
#endif

        if( robCtl->getMasterState()!= state )
        {
            state= robCtl->getMasterState();

            ui->label_master_state->setStyleSheet( "background-color:gray;" );
            switch(state){
            case eMasterErr_LOCK:
                ui->label_master_state->setText( "eMasterErr_LOCK" );
                ui->label_master_state->setStyleSheet( "background-color:red;" );
                break;
            case eMasterErr:
                ui->label_master_state->setText( "ERROR" );
                ui->label_master_state->setStyleSheet( "background-color:red;" );
                break;
            case eMasterBootstrap:
                ui->label_master_state->setText( "Bootstrap" );
                break;
            case eMasterUnknown:
                ui->label_master_state->setText( "Unknown" );
                break;
            case eMasterInit:
                ui->label_master_state->setText( "Init" );
                break;
            case eMasterPreOP:
                ui->label_master_state->setText( "PreOP" );
                break;
            case eMasterSafeOP:
                ui->label_master_state->setText( "SafeOP" );
                break;
            case eMasterOP:
                ui->label_master_state->setText( "OP" );
                ui->label_master_state->setStyleSheet( "background-color:lightgreen;");
                break;
            }

            qDebug()<<"state=="<<state;
        }
        for(int i=0;i<rob->ethercatAxis.size();i++)
        {
            axis_box[i]->setText( QString::number( rob->ethercatAxis.at(i)->logicMotors[0]->actPosition ) );
        }
    }

    //status word
    int axisId=ui->comboBox_axis_id->currentIndex();
    if(axisId<rob->ethercatAxis.size())
    {
        displayStatusWord(rob->ethercatAxis.at(axisId)->logicMotors[0]->stateWord,
                rob->ethercatAxis.at(axisId)->logicMotors[0]->controlWord);
        ui->lineEdit_mode->setText(QString::number(rob->ethercatAxis.at(axisId)->logicMotors[0]->modeOfOperation));

    }


}

void testForm::setDoValue(bool checked)
{
    qDebug()<<"testForm::setDoValue";
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value(),NULL );
    if(rob==NULL)
        return ;

    QCheckBox* box = qobject_cast<QCheckBox *>(sender());
    if( box )
    {
        int index =  box->text().toInt();
        QString str= ((QGroupBox*)box->parent())->title();
        if( str=="DO" )
        {
            //BUG,物理ＩＯ获取的ＤＯ比控件状态延迟的话，会错误执行下面的设置。
            rob->logicRobotIo->setDo( index, box->isChecked() );
            qDebug()<<"testForm DO index    :"  << index << checked <<  rob->logicRobotIo->ioDi  << rob->logicRobotIo ->ioDo ;
        }
    }

}

void testForm::setVirtualDiState(bool checked)
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value(),NULL );
    if(rob==NULL)
        return ;

    QCheckBox* box = qobject_cast<QCheckBox *>(sender());
    if( box )
    {
        int index =  box->text().toInt();
        QString str= ((QGroupBox*)box->parent())->title();
        if( str=="virtualDi" ){
            rob->logicRobotIo->setDi( index, box->isChecked() );
            qDebug()<<"virtualDi index    :"  << index << checked <<  rob->logicRobotIo->ioDi
                   << rob->logicRobotIo ->ioDo ;
        }
    }
}

void testForm::on_checkBox_servo_on_toggled(bool checked)
{
    if( checked )
        robCtl->servoOnRobot( ui->spinBox_robot->value());
    else
        robCtl->servoOffRobot( ui->spinBox_robot->value());
}

void testForm::on_pushButton_clearError_clicked()
{
    robCtl->resetErrorRobot( ui->spinBox_robot->value() );
}

void testForm::on_checkBox_dir_toggled(bool checked)
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value() );
    if(rob){
        rob->test_dir_set=checked;
    }
}

void testForm::on_pushButton_run_pressed()
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value() );
    if(rob){
        rob->test_run_set=true;
        qDebug()<<"rob->test_run_set"<<rob->test_run_set<<ui->spinBox_robot->value();
    }
}

void testForm::on_pushButton_run_released()
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value() );
    if(rob){
        rob->test_run_set=false;
        qDebug()<<"rob->test_run_set"<<rob->test_run_set<<ui->spinBox_robot->value();
    }
}

void testForm::on_checkBox_run_toggled(bool checked)
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value() );
    if(rob){
        rob->test_run_set=checked;
        ui->comboBox_axis->setEnabled( !checked );
        ui->spinBox_robot->setEnabled( !checked );
    }
}

void testForm::on_spinBox_num_valueChanged(int arg1)
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value() );
    if(rob){
        rob->test_target_increment_set=arg1;
    }
}

void testForm::on_checkBox_allaxis_toggled(bool checked)
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value() );
    if(rob){
        if(checked){
            rob->test_axis_set=-1;
        }else{
            rob->test_axis_set=ui->comboBox_axis->currentIndex();
        }
        qDebug()<<"choose axis:"<<rob->test_axis_set;
    }
}

void testForm::on_horizontalSlider_sliderMoved(int position)
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value() );
    if(rob){
       rob->test_acceleration_set=position;
       qDebug()<<"acc : "<<position;
    }
}

void testForm::on_pushButton_stop_clicked()
{
    robCtl->quickStopRobot(-1);
    qDebug()<<"quick stop ! ";
}

void testForm::on_comboBox_axis_currentIndexChanged(int index)
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value() );
    if(rob){
        if( !ui->checkBox_allaxis->isChecked() ){
            rob->test_axis_set= index;
        }
        qDebug()<<"choose axis:"<<rob->test_axis_set;
    }
}

void testForm::on_spinBox_dir_ms_valueChanged(int arg1)
{
    RobotBase*rob=robCtl->robotsMap.value( ui->spinBox_robot->value() );
    if(rob){
        rob->test_dir_ms= arg1;
    }
}

void testForm::on_checkBox_updateTimer_clicked(bool checked)
{
    if(true==checked)
    {
       timer->start(100);
    }
    else
    {
        timer->stop();
    }
}

void testForm::on_pushButton_setControlWord_clicked()
{
    bool isOk;
    unsigned short controlWord=ui->lineEdit_controlWord->text().toInt(&isOk,16);

    if(ui->checkBox_oneAxis->isChecked())
    {
        robCtl->setControlWordDebug_axis(ui->spinBox_robot->value(),controlWord,ui->comboBox_axis_id->currentIndex());
    }
    else
    {
        robCtl->setControlWordDebug(ui->spinBox_robot->value(),controlWord);
    }
    QMessageBox::information(NULL, "ok", "ok", QMessageBox::Yes );
}

void testForm::displayStatusWord(unsigned short wordIn,unsigned short contrlWordIn)
{
    QString tmp;
    tmp.clear();
    tmp.sprintf("%02x",wordIn);
    ui->lineEdit_controlWord_show->setText(tmp+"h");

    tmp.clear();
    tmp.sprintf("%02x",contrlWordIn);
    ui->lineEdit_controlWord_display->setText(tmp+"h");

    for(int j=0;j< 16 ; j++)
    {
        statusWord_box[j]->setChecked(wordIn&1);
        wordIn=wordIn>>1;

        controlWord_box[j]->setChecked(contrlWordIn&1);
        contrlWordIn=contrlWordIn>>1;
    }
}
